package main

import (
	"fmt"
	"gitee.com/sunny-zhangqiang/zcache/xhttp"
	"time"
)

var (
	tp = xhttp.Transport{}
)

func test(rw xhttp.ResponseWriter, r *xhttp.Request) {
	if r.Host != "www.test.com" {
		panic(r.Host)
	}

	if r.URL.Path != "/1.txt" {
		panic(r.URL.Path)
	}

	if r.URL.RawQuery != "a=1&b=2" {
		panic(r.URL.RawQuery)
	}

	if r.Header.Get("test") != "abc" {
		panic("get request header failed")
	}

	rw.Header().Add("test", "123")
	rw.WriteHeader(xhttp.StatusOK)
	rw.Write([]byte("success"))
}

func main() {
	go func() {
		xhttp.DefaultServeMux.HandleFunc("/", test)
		err := xhttp.ListenAndServe("127.0.0.1:9999", nil)
		if err != nil {
			panic(err)
		}
	}()

	time.Sleep(time.Second)

	req, err := xhttp.NewRequest(xhttp.MethodGet, "http://127.0.0.1:9999/1.txt", nil)
	req.Host = "www.test.com"
	// 必须这样使用query.
	q := req.URL.Query()
	q.Add("a", "1")
	q.Add("b", "2")
	req.URL.RawQuery = q.Encode()
	req.Header.Set("test", "abc")
	if err != nil {
		panic(err)
	}

	resp, err := tp.RoundTrip(req)
	if err != nil {
		panic(err)
	}

	if resp.StatusCode != 200 {
		panic(resp.StatusCode)
	}

	if resp.Header.Get("test") != "123" {
		panic(resp.Header.Get("test"))
	}

	buf := make([]byte, 512)
	n, err := resp.Body.Read(buf)
	if n == 0 {
		if err != nil {
			panic(err)
		}
	}

	buf = buf[:n]
	if string(buf) != "success" {
		panic(string(buf))
	}

	fmt.Println("test success")
}
